package com.zxp.utils.fileUtils;

import java.io.File;

public class FileDeleter {

    /**
     * Delete a file or folder
     *
     * @param filePath The path of the file or folder to delete
     * @return true if successfully deleted, false if deletion fails or the path does not exist
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);

        // If the file or folder does not exist, return false
        if (!file.exists()) {
            System.out.println("File or folder '" + filePath + "' does not exist.");
            return false;
        }

        // If it is a file, delete it directly
        if (file.isFile()) {
            boolean deleted = file.delete();
            if (deleted) {
                System.out.println("File '" + filePath + "' deleted successfully.");
            } else {
                System.out.println("Failed to delete file '" + filePath + "'.");
            }
            return deleted;
        }

        // If it is a folder, recursively delete
        boolean deleted = deleteFolder(file);
        if (deleted) {
            System.out.println("Folder '" + filePath + "' deleted successfully.");
        } else {
            System.out.println("Failed to delete folder '" + filePath + "'.");
        }
        return deleted;
    }

    /**
     * Recursively delete a folder
     *
     * @param folder The folder path
     * @return true if successfully deleted, false if deletion fails
     */
    private static boolean deleteFolder(File folder) {
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // Recursively delete subfolders
                    deleteFolder(file);
                } else {
                    // Delete files
                    file.delete();
                }
            }
        }
        // Delete the empty folder
        return folder.delete();
    }

    public static void main(String[] args) {
        // Example usage
        String filePath = "exampleFile.txt";
        deleteFile(filePath);

        String folderPath = "exampleFolder";
        deleteFile(folderPath);
    }
}
